from django import forms
from django.db.models import Q

from login import constants
from login.models import User


class RegisterForm(forms.Form):
    username = forms.CharField(label='用户名', max_length=20, min_length=5,
                               error_messages={"min_length": "用户名长度要大于5", "max_length": "用户名长度要小于20",
                                               "required": "用户名不能为空"})
    password = forms.CharField(label='密码', max_length=20, min_length=6,
                               error_messages={"min_length": "密码长度要大于6", "max_length": "密码长度要小于20",
                                               "required": "密码不能为空"})
    password_repeat = forms.CharField(label='确认密码', max_length=20, min_length=6,
                                      error_messages={"min_length": "密码长度要大于6", "max_length": "密码长度要小于20",
                                                      "required": "密码不能为空"})
    email = forms.EmailField(required=True, error_messages={'required': "邮箱不能为空"})

    def clean(self):
        cleaned_data = super().clean()
        passwd = cleaned_data.get('password')
        passwd_repeat = cleaned_data.get('password_repeat')
        if passwd != passwd_repeat:
            raise forms.ValidationError("两次密码不一致")


class LoginForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField(label='密码', max_length=20, min_length=6,
                               error_messages={"min_length": "密码长度要大于6",
                                               "max_length": "密码长度要小于20",
                                               "required": "密码不能为空"})
    remember = forms.BooleanField(required=False)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(LoginForm, self).__init__(*args, **kwargs)

    def clean(self):
        # 获取清洗数据后的参数
        cleaned_data = super(LoginForm, self).clean()
        user_email = cleaned_data.get('email')
        user_password = cleaned_data.get('password')
        user_remember = cleaned_data.get('remember')
        # 查询数据库，并校验、设置会话保存时间
        query_user = User.objects.filter(Q(email=user_email)).first()
        if query_user:
            if query_user.password == user_password:
                if user_remember:
                    self.request.session.set_expiry(constants.USER_SESSION_EXPIRES)
                else:
                    self.request.session.set_expiry(0)
            else:
                raise forms.ValidationError('密码错误，请重新输入')
        else:
            raise forms.ValidationError('用户账号不存在，请重新输入')
